<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								订单明细
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- 							<el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="所属订单" prop="salesOrder">
							<el-select @clear="selectClear('salesOrder')" v-model="formData.salesOrder"
								@change="(value:any)=>selectChange(value,'salesOrder')" multiple ref="salesOrder"
								clearable>
								<el-option v-for="item in salesOrderOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="salesOrderOption[salesOrderIndex]?.color">
													<component :is="salesOrderOption[salesOrderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{salesOrderOption[salesOrderIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="下单产品" prop="product">
							<el-select @clear="selectClear('product')" v-model="formData.product"
								@change="(value:any)=>selectChange(value,'product')" multiple ref="product" clearable>
								<el-option v-for="item in productOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="productOption[productIndex]?.color">
													<component :is="productOption[productIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{productOption[productIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="下单数量" prop="quantityOrdered">
									<el-input @input="onInput" placeholder="请填写" type="number"
										v-model="formData.quantityOrdered" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="折后单价" prop="discountedPrice">
									<el-input placeholder="请填写" type="number" v-model="formData.discountedPrice"
										clearable>
										<template #suffix>
											<e-text>元</e-text>
										</template>
									</el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-form-item label="金额小计" prop="subtotalAmount">
							<el-input placeholder="自动计算结果" type="number" v-model="formData.subtotalAmount" readonly
								clearable></el-input>
						</el-form-item>
						<el-form-item label="备注" prop="notes">
							<el-input placeholder="请填写" type="text" v-model="formData.notes" clearable></el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>成本</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="成本单价" prop="costPrice">
									<el-input placeholder="请填写" type="number" v-model="formData.costPrice" clearable>
										<template #suffix>
											<e-text>元</e-text>
										</template>
									</el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="商品成本" prop="productCost">
									<el-input placeholder="自动计算结果" type="number" v-model="formData.productCost" disabled
										clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="实际销售数量" prop="actualSalesQuantity">
									<el-input placeholder="自动计算结果" type="number" v-model="formData.actualSalesQuantity"
										disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="退货数量" prop="returnQuantity">
									<el-input placeholder="自动计算结果" type="number" v-model="formData.returnQuantity"
										disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>发货情况</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="待申请发货数量" prop="pendingShipmentQuantity">
									<el-input type="number" v-model="formData.pendingShipmentQuantity"
										placeholder="自动计算结果" disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="已发货数量" prop="shippedQuantity">
									<el-input placeholder="自动计算结果" type="number" v-model="formData.shippedQuantity"
										disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="已签收数量" prop="receivedQuantity">
									<el-input placeholder="自动计算结果" type="number" v-model="formData.receivedQuantity"
										disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="待签收数量" prop="pendingReceiptQuantity">
									<el-input type="number" v-model="formData.pendingReceiptQuantity"
										placeholder="自动计算结果" disabled clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>退货情况</div>
						</div>
						<el-form-item label="已退货数量" prop="returnedQuantity">
							<el-input placeholder="自动计算结果" type="number" v-model="formData.returnedQuantity" disabled
								clearable></el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ref, onMounted, reactive, shallowRef, Ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import { ArrowDown, UserFilled, Plus, WalletFilled, UploadFilled, GoodsFilled } from '@element-plus/icons-vue';
	import { ElLoading } from 'element-plus';
	import request from '../../../utils/request';
	import { ElMessage, FormInstance, UploadProps } from 'element-plus';
	import { colors, findIndexByLabel, isEmpty, removeEmptyProperties } from '../../../utils/index';
	import { formatDate } from '../../../utils/date';
	import { formatNumber, mergeObjects } from '../../../utils/index';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	import { useSelect } from '../../../utils/mixins';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	// 表单
	const formData = ref({
		salesOrder: [],
		salesOrderId: null,
		orderId: null,
		product: [],
		productId: null,
		quantityOrdered: null,
		discountedPrice: null,
		subtotalAmount: null,
		notes: null,
		costPrice: null,
		productCost: null,
		actualSalesQuantity: null,
		returnQuantity: null,
		pendingShipmentQuantity: null,
		shippedQuantity: null,
		receivedQuantity: null,
		pendingReceiptQuantity: null,
		returnedQuantity: null,
	});
	//
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//
	//所属订单
	const salesOrderOption = ref([]);
	const salesOrderIndex = ref(-1);
	const salesOrder = ref(null);
	//下单产品
	const productOption = ref([]);
	const productIndex = ref(-1);
	const product = ref(null);
	//
	//
	const rules = reactive({
		salesOrder: [{ required: true, message: '所属订单必选！', trigger: ['blur', 'change'] }],
		product: [{ required: true, message: '下单产品必选！', trigger: ['blur', 'change'] }],
		quantityOrdered: [{ required: true, message: '下单数量必填！', trigger: ['blur', 'change'] }],
		discountedPrice: [{ required: true, message: '折后单价必填！', trigger: ['blur', 'change'] }],
		subtotalAmount: [{ required: true, message: '金额小计必填！', trigger: ['blur', 'change'] }],
		notes: [],
		costPrice: [{ required: true, message: '成本单价必填！', trigger: ['blur', 'change'] }],
		productCost: [],
		actualSalesQuantity: [],
		returnQuantity: [],
		pendingShipmentQuantity: [],
		shippedQuantity: [],
		receivedQuantity: [],
		pendingReceiptQuantity: [],
		returnedQuantity: [],
		pendingPaymentAmount: [],

	});
	//
	onMounted(() => {
		// getCustomer();
	});
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getCustomer();
			//
			if (result) {
				getOrderList();
				getProductList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	const getCustomer = async () => {
		if (!route.query.id) {
			return true;
		}
		const result = await request({
			url: '/login/selectOrderDetail',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getCustomer--->', result);
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'salesOrder', //哪一个下拉框，根据ref
			option: salesOrderOption, //下拉列表选项
			indexVar: salesOrderIndex, //当前选中项
			idVar: 'salesOrderId', //当前id值
			blurRef: salesOrder, //ref
		}, {
			type: 'product',
			option: productOption,
			indexVar: productIndex,
			idVar: 'productId',
			blurRef: product,
			fun: getProduct
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取所有订单信息
	const getOrderList = async () => {
		const result = await request({
			url: '/login/selectSaleOrderAll',
			params: pageData.value,
		});
		//
		console.log('getOrderList --->', result);
		salesOrderOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			salesOrderOption.value.push({
				label: `${item.orderNumber}_${formatNumber(item.orderTotalAmount, '元')}_${item.status} | ${item.customer.customerName}`,
				value: item.orderId,
				icon: WalletFilled,
				color: '#82b51b'
			});
			if (formData.value.salesOrderId === item.orderId) {
				formData.value.salesOrder = [item.orderId];
				salesOrderIndex.value = key;
			}
		});
	}
	//获取所有产品
	const getProductList = async () => {
		const result = await request({
			url: '/login/selectProductAll',
			params: pageData.value,
		});
		//
		console.log('getProductList --->', result);
		productOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			productOption.value.push({
				label: `${item?.productName}${item?.model} | 在库${item?.currentInventory}件`,
				value: item?.productId,
				icon: GoodsFilled,
				color: '#5283ff'
			});
			if (formData.value.productId === item.productId) {
				formData.value.product = [item.productId];
				productIndex.value = key;
				getProduct(item.productId);
			}
		})
		//
	}
	//根据id获取产品
	const getProduct = async (id : string | number, key : number = -1) => {
		if (!id) {
			return;
		}
		const result = await request({
			url: '/login/selectProduct',
			params: {
				id
			}
		});
		//
		console.log('getProduct --->', result);
		computeAll(result.data.t);
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				delete formData.value.salesOrder;
				delete formData.value.product;
				let type = '';
				if (!route.query.id) {
					type = '/saveOrderDetail';
				} else {
					type = '/updateOrderDetail';
				}
				//
				const result = await request({
					url: '/login' + type,
					data: formData.value,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
					// formData.value = mergeObjects(formData.value, result.data.t);
					// openDialog();
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//
	const onInput = (e) => {
		console.log('onInput --->', e);
		computeAll();
	}
	const computeAll = (data ?: any) => {
		const { sellingPrice, costPrice, } = data;
		// 折后单价
		 formData.value.discountedPrice= sellingPrice?sellingPrice : formData.value.discountedPrice;
		// 金额小计
		formData.value.subtotalAmount = formData.value.quantityOrdered * formData.value.discountedPrice;
		// 成本单价
		formData.value.costPrice = costPrice?costPrice : formData.value.costPrice;
		// 商品成本
		formData.value.productCost = formData.value.quantityOrdered * formData.value.costPrice;
		// 实际销售数量
		formData.value.actualSalesQuantity = 0;
		// 退货数量
		formData.value.returnQuantity = 0;
		// 待申请发货数量
		formData.value.pendingShipmentQuantity = 0;
		// 已发货数量
		formData.value.shippedQuantity = 0;
		// 已签收数量
		formData.value.receivedQuantity = 0;
		// 待签收数量
		formData.value.pendingReceiptQuantity = 0;
		// 已退货数量
		formData.value.returnedQuantity = 0;
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>